package cn.t.modules.scheduler.core;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author 陶敏麒
 * @date 2023/8/28 17:12
 */
@Component
public class SpringBeanContext implements ApplicationContextAware {
    private static ApplicationContext context;

    /**
     * 是否初始化完成
     * @return true 初始化完成
     */
    public static boolean hasInitialized() {
        return context != null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 这里用init可以解除警告,虽然不这么做也没事
        init(applicationContext);
    }

    /**
     * 初始化上下文
     * @param applicationContext spring上下文
     */
    private static void init(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    /**
     * 根据类型获取bean
     * @param beanClass 类型
     * @param <T> 类型
     * @return bean
     */
    public static <T> T getBean(Class<T> beanClass) {
        if (context == null) {
            throw new RuntimeException("SpringBeanContext has not initialized...");
        }
        return context.getBean(beanClass);
    }
}
